package cn.ray.springframework.beans.factory.support;

import cn.hutool.core.bean.BeanException;
import cn.ray.springframework.beans.factory.DisposableBean;
import cn.ray.springframework.beans.factory.config.BeanReference;
import cn.ray.springframework.beans.factory.config.SingletonBeanRegistry;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

//主要实现getSingleton方法，并实现了一个受保护的addSingleton，接受继承此类的其他类调用
public class DefaultSingletonBeanRegistry implements SingletonBeanRegistry {

    //定义Null_object 标记对象
    protected static final Object NULL_OBJECT=new Object();
    private Map<String, Object> singletonObjects = new HashMap<>();
    private final Map<String, DisposableBean> disposableBeans = new HashMap<>();

    @Override
    public Object getSingleton(String beanName) {
        return singletonObjects.get(beanName);
    }

    protected void addSingleton(String beanName, Object singletonObject) {
        singletonObjects.put(beanName, singletonObject);
    }

    public void registerDisposableBean(String name, DisposableBean bean) {
        disposableBeans.put(name, bean);
    }

    public void destroySingletons() {
        Set<String> keyset = this.disposableBeans.keySet();
        Object[] disposableBeanNames = keyset.toArray();

        for (int i = disposableBeanNames.length - 1; i >= 0; i--) {
            Object beanName = disposableBeanNames[i];
            DisposableBean disposableBean = disposableBeans.remove(beanName);

            try {
                disposableBean.destroy();
            } catch (Exception e) {
                throw new BeanException("Destroy method on bean with name '" + beanName + "' threw an exception", e);
            }
        }
    }
}
